<?php

namespace app\controller;

use app\BaseController;
use app\model\BocMaterials;
use app\model\BocOrder;
use app\model\BocOrderList;

class Order extends BaseController
{
    public function order_list()
    {
        $page = $this->request->get('page');
        // $order_m = m('BocOrder');
        $order_m = new BocOrder();
        $res = $order_m->paginate(5, false, [], $page);
        $data = $res->toArray();

        return json(['code' => 200, 'data' => $data]);
    }

    public function change_company()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (!$post['gys_order']) {
                return json(['code' => 400, 'msg' => '参数错误']);
            }
            $materials_m = new BocMaterials();
            $list = $materials_m->where(['gys_order' => $post['gys_order'], 'state' => 1, 'is_deleted' => 1])->select()->toArray();

            return result($list);
        }
    }

    public function change_order_state()
    {
        if ($this->request->isGet()) {
            $get = $this->request->get();
            try {
                $order_m = new BocOrder();
                $state = $order_m->where(['id' => $get['id']])->save(['state' => $get['state']]);
                if (!$state) {
                    throw new \Exception($state);
                }

                return result($state);
            } catch (\Exception $e) {
                return json(['code' => 400, 'msg' => $e->getMessage()]);
            }
        }
    }

    /*
     * 订单添加
     */
    public function order_add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();

            $order = 'order_'.time().rand(10001, 99999);
            $order_m = new BocOrder();
            $orderlist_m = new BocOrderList();
            $orderres = $order_m->save(['order' => $order, 'title' => $post['title']]);
            foreach ($post['order'] as $k => $v) {
                array_push($v, $order);
                $orderlist_m->save(
                    [
                        'order' => $order,
                        'gys_order' => $v['gys_order'],
                        'title' => $v['title'],
                        'price' => $v['price'],
                        'count' => $v['count'],
                        ]
                );
            }

            return result($orderres);
        }
    }

    public function getone_order()
    {
        if ($this->request->isGet()) {
            $post = $this->request->get();
            $order_m = new BocOrder();
            $orderlist_m = new BocOrderList();
            $data['list'] = $order_m->where(['order' => $post['order']])->order('id desc')->find();
            $data['arr'] = $orderlist_m->where(['order' => $post['order']])->select();

            return result($data);
        }
    }
}
